package net.dgg.iboss.sc.backservice.task.service;


import net.dgg.iboss.base.util.DateUtil;
import net.dgg.iboss.sc.backservice.task.constant.ScProductConstant;
import net.dgg.iboss.sc.backservice.task.dao.AssistantDao;
import net.dgg.iboss.sc.backservice.task.dao.ProductOrderDao;
import net.dgg.iboss.sc.backservice.task.dao.ProductTimeStatusDao;
import net.dgg.iboss.sc.backservice.task.entity.*;
import net.dgg.iboss.sc.backservice.task.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <p>@Title 办理中Service</p>
 * <p>@Description 办理中Service</p>
 * <p>@Version 1.0.0 版本号</p>
 * <p>@author maoquanyi</p>
 * <p>@date 2018年08月13日</p>
 * <p>Copyright © dgg group.All Rights Reserved. 版权信息</p>
 */
@Service
public class ZzInProcessService {

    @Autowired
    private AssistantDao assistantDao;
    @Autowired
    private ProductTimeStatusDao productTimeStatusDao;
    @Autowired
    private FlowService flowService;
    @Autowired
    private CommonService commonService;
    @Autowired
    private UserService usersService;
    @Autowired
    private ProductOrderDao productOrderDao;
    @Autowired
    private NodeTimeOutPunishService nodeTimeOutPunishService;

    /**
     * <p>@Description 根据生产id查询协单人员</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/8/16 0016 16:41 创建时间</p>
     * <p>@return</p>
     */
    public List<Assistant> queyScAssistantList(Long id) {
        List<Assistant> scAssistantList = assistantDao.query(new HashMap<String, Object>() {{
            put("scProductOrderId", id);
        }});
        return scAssistantList;
    }

    /**
     * 节点即将超期提醒
     */
    public void overDueRminder(){
        List<ProductTimeStatus> list = productTimeStatusDao.queryOverdue();
        if(list.size()>0){
            for(ProductTimeStatus productTimeStatus : list){
                Node node = flowService.queyNodeListById(productTimeStatus.getNodeId(),productTimeStatus.getId());
                if(node.getIsWarning()==1){
                    ProductOrder scProductOrder = productOrderDao.selectByPrimaryKey(productTimeStatus.getId());
                    List<UserEntity> users = new ArrayList<>();
                    //流程人员
                    users.add( usersService.findUserById(scProductOrder.getFlowUserId()));
                    //签单商务
                    UserEntity signUser = usersService.findUserById(scProductOrder.getSignUserId());
                    if(signUser!=null){
                        users.add(signUser);
                    }
                    //商务经理
                    String[] codes = new String[]{"SWJL"};
                    List<UserEntity> signUsers = usersService.findUserByRoleCodesAndOrgs(codes, 0, scProductOrder.getSignUserOrgId());
                    if(signUsers!=null && signUsers.size()>0){
                        users.addAll(signUsers);
                    }
                    //后台经理
                    String[] flowCodes = new String[]{"ZZSC_HTMANAGER"};
                    List<UserEntity> flowUser = usersService.findUserByRoleCodesAndOrgs(flowCodes, 0, scProductOrder.getFlowUserOrgId());
                    //您好，生产订单{生产订单编号}{客户名称}{订单产品}，{节点名称}节点明天将超期，请及跟踪时处理！
                    String msg[]=new String[]{productTimeStatus.getScProductOrderNo(),scProductOrder.getCustomerName(),scProductOrder.getProductName(),node.getName()};
                    commonService.sendMsg(users,msg,"ZZSC_JJCQ");
            }
            }
        }
    }

    /**
     * 节点超期提醒
     */
    public void nodeTimeOutAlert(){
        List<ProductTimeStatus> list = productTimeStatusDao.queryNodeTimeOut();
        if(list.size()>0){
            for(ProductTimeStatus productTimeStatus : list){
                ProductOrder productOrder = productOrderDao.selectByPrimaryKey(productTimeStatus.getId());
                if(StringUtils.isEmpty(productOrder.getFlowContent())){
                    continue;
                }
                List<Long> idList = new ArrayList<>();
                idList.add(productTimeStatus.getId());
                productTimeStatusDao.updateNodeTimeStatus(ScProductConstant.TIME_OUT,idList);
                Node node = flowService.queyNodeListByName(productTimeStatus.getNodeName(),productTimeStatus.getId());
                List<UserEntity> userList = new ArrayList<>();
                //签单商务
                UserEntity signUser = usersService.findUserById(productOrder.getSignUserId());
                if(signUser!=null){
                    userList.add(signUser);
                }
                //商务经理
                String[] codes = new String[]{"SWJL"};
                List<UserEntity> signUsers = usersService.findUserByRoleCodesAndOrgs(codes, 0, productOrder.getSignUserOrgId());
                if(signUsers!=null && signUsers.size()>0){
                    userList.addAll(signUsers);
                }
                if(productOrder.getFlowUserId()!=null){
                    //流程人员
                    userList.add( usersService.findUserById(productOrder.getFlowUserId()));
                    //后台经理
                    String[] flowCodes = new String[]{"ZZSC_HTMANAGER"};
                    if(productOrder.getFlowUserOrgId()!=null){
                        List<UserEntity> flowUser = usersService.findUserByRoleCodesAndOrgs(flowCodes, 0, productOrder.getFlowUserOrgId());
                        if(flowUser!=null && flowUser.size()>0) {
                            userList.addAll(flowUser);
                        }
                    }
                }
                Date nodeEndDate = productTimeStatus.getNodeEndTime();
                Integer nodeDay =(int) Math.ceil((new Date().getTime()-nodeEndDate.getTime())/(3600*1000*24))+1;
                Integer remainDays = flowService.getAfterKyeNodeDays(productTimeStatus.getId());
                //消息 您好，生产订单{生产订单编号}{客户名称}{订单产品}，{节点名称}节点已超期x天，合同截止日期为{合同截止时间}，实际生产预计还需x天（流程中该节点之后的关键节点总天数）请及跟踪时处理！
                String msg[]=new String[]{productTimeStatus.getScProductOrderNo(),productOrder.getCustomerName(),null != productOrder.getProductName() ? productOrder.getProductName():" ",node.getName(),nodeDay.toString(), DateUtil.dateToString(productOrder.getContractEndDate(),"yyyy-MM-dd"),remainDays.toString()};
                commonService.sendMsg(userList,msg,"ZZSC_JDCQ_TX");
            }
        }
    }
    public void nodeTimeOutPunish(){
            List<ProductTimeStatus> list = productTimeStatusDao.queryNodeTimeOutNoPunish();
            if (list.size() > 0) {
                for (ProductTimeStatus productTimeStatus : list) {
                    ProductOrder productOrder = productOrderDao.selectByPrimaryKey(productTimeStatus.getId());
                    Node node = flowService.queyNodeListById(productTimeStatus.getNodeId(), productTimeStatus.getId());
                    this.nodeTimeOutPunish(productOrder, node, productTimeStatus);
                }
            }
    }
    @Transactional
    public void nodeTimeOutPunish(ProductOrder order,Node node,ProductTimeStatus productTimeStatus){
        List<TimeoutPunishDto> list = new ArrayList<>();
        TimeoutPunishDto timeoutPunishDto = new TimeoutPunishDto();
        timeoutPunishDto.setBusinessCode(order.getBusinessTypeCode());
        timeoutPunishDto.setBusinessName(order.getBusinessTypeName());
        timeoutPunishDto.setFlowUserId(order.getFlowUserId());
        timeoutPunishDto.setFlowUserName(order.getFlowUserName());
        timeoutPunishDto.setProductOrgId(order.getProductOrgId());
        timeoutPunishDto.setProductOrgName(order.getProductOrgName());
        timeoutPunishDto.setOrgId(order.getFlowUserOrgId());
        timeoutPunishDto.setOrgName(order.getFlowUserOrgName());
        timeoutPunishDto.setOrderId(order.getOrderId());
        timeoutPunishDto.setOrderNo(order.getOrderNo());
        timeoutPunishDto.setProductOrderId(order.getId());
        timeoutPunishDto.setProductOrderNo(order.getScProductOrderNo());
        timeoutPunishDto.setCustomerId(order.getCustomerId());
        timeoutPunishDto.setCustomerName(order.getCustomerName());
        timeoutPunishDto.setCustomerNo(order.getCustomerNo());
        timeoutPunishDto.setCustomerPhone(order.getCustomerPhone());
        timeoutPunishDto.setNoId(node.getId());
        timeoutPunishDto.setNoCode(node.getCode());
        timeoutPunishDto.setNoName(node.getName());
        timeoutPunishDto.setVersion(node.getVersion());
        timeoutPunishDto.setTimeOutTime(productTimeStatus.getNodeEndTime());
        timeoutPunishDto.setPunishTime(new Date());
        list.add(timeoutPunishDto);
        Map param = new HashMap(1);
        param.put("timeoutPunishListDtos",list);
        Integer code = nodeTimeOutPunishService.nodeTimeOutPunish(param);
        if(code==0){
            productOrderDao.updatePunishStatus(order.getId());
            if("成都资质事业部".equals(order.getProductOrgName())){
                //发送扣罚消息
                try {//不让影响其他功能
                    List<UserEntity> users = new ArrayList<>();
                    //扣罚人
                    UserEntity user = usersService.findUserById(order.getFlowUserId());
                    users.add(user);
                    //1.生产订单节点奖罚：您好，{生产订单编号}{客户名称}{订单产品}，xx节点超期产生扣罚，请查看确认。
                    String msg[] = new String[]{order.getScProductOrderNo(),order.getCustomerName(),order.getProductName(),node.getName()};
                    commonService.sendMsg(users, msg, "ZZSC_NODE_PUNISH_ALERT");//匹配模板
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
